package me.zhengjie.modules.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiaofang.applet.service.other.domain.CityCompany;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.applet.service.other.util.DateTypeUtil;
import com.qiaofang.applet.service.property.domain.Property;
import com.qiaofang.common.request.DataRequest;
import com.qiaofang.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.quartz.service.constants.SyncConstants;
import me.zhengjie.modules.quartz.service.dto.SyncCommon;
import me.zhengjie.modules.sync.request.SysFieldSyncRequest;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @Author: youqing.yang
 * @Create: 2021/01/22 10:24
 * @Description:
 **/
@Slf4j
@Component
public class PropertyTypeSyncTask {

    private static final String PRO_PROPERTY_TYPE_SYNC_API = "/api/dataprocessing/syncData/getPropertyTypeMap";

    @Autowired
    private CorporationService corporationService;

    @Autowired
    private MongoTemplate mongoTemplate;

    private RestTemplate template;

    {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(300000);
        requestFactory.setReadTimeout(300000);
        template = new RestTemplate(requestFactory);
    }

    public void run() {
        log.info("PropertyTypeSyncTask run start");
        Corporation corporation = new Corporation();
        corporation.setDeleted(Boolean.FALSE);
        corporation.setV20Flag(Boolean.FALSE);
        Iterable<Corporation> list = corporationService.findAll(Example.of(corporation));
        list.forEach(item -> {
            String corporationCode = item.getCorporationCode();
            if (StringUtil.isEmpty(item.getPullDomain())) {
                log.error("集团:{} 的同步数据域名未配置", corporationCode);
                return;
            }

            Criteria criteria = Criteria.where("corporationCode").is(corporationCode).and("status").is(1);
            List<CityCompany> companies = mongoTemplate.find(new Query(criteria), CityCompany.class);
            companies.forEach(company -> {
                SyncCommon syncCommon = new SyncCommon();
                syncCommon.setCorporationCode(item.getCorporationCode());
                syncCommon.setAppId(item.getPullAppId());
                syncCommon.setAppKey(item.getPullAppKey());
                syncCommon.setDomain(item.getPullDomain());
                syncCommon.setCityCode(company.getCityCode());
                syncCommon.setCompanyUuid(company.getCompanyUuid());

                long start = System.currentTimeMillis();
                log.info("开始处理公司:{}的房源类型数据，开始时间:{}", company.getCompanyUuid(), new Date());
                updateProperty(syncCommon, PRO_PROPERTY_TYPE_SYNC_API);
                log.info("完成处理公司:{}的房源类型数据，耗时:{}ms", company.getCompanyUuid(), System.currentTimeMillis() - start);
            });
        });
        log.info("PropertyTypeSyncTask run end");
    }

    private void updateProperty(SyncCommon syncCommon, String apiUrl) {
        String companyUuid = syncCommon.getCompanyUuid();
        Criteria criteriaInit = Criteria.where("companyUuid").is(companyUuid)
                .and("usageTypeName").exists(true);
        Date timing = null;
        if (mongoTemplate.count(new Query(criteriaInit), Property.class) > 0){
            //表示不是初始执行，需要传入时间参数
            timing = DateTypeUtil.getDayZero(DateUtils.addDays(new Date(), -1));
        }
        JSONObject listMap = httpRequestData(new SysFieldSyncRequest(timing), syncCommon, apiUrl);
        if (CollectionUtils.isEmpty(listMap)){
            return;
        }
        Set<Map.Entry<String, Object>> entries = listMap.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            String usageTypeName = entry.getKey();
            List<String> propertyUuidList = (List<String>) entry.getValue();
            Criteria criteria = Criteria.where("companyUuid").is(companyUuid)
                    .and("propertyUuid").in(propertyUuidList);
            Update update = new Update();
            update.set("usageTypeName", usageTypeName);
            mongoTemplate.updateMulti(new Query(criteria), update, Property.class);
        }
    }

    private HttpHeaders getHeaders(SyncCommon syncCommon) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("X-AUTH-APP-ID", syncCommon.getAppId());
        headers.add("X-AUTH-KEY", syncCommon.getAppKey());
        headers.add("companyUuid", syncCommon.getCompanyUuid());
        log.info("========>headers:{}", JSON.toJSONString(headers));
        return headers;
    }

    private JSONObject httpRequestData(SysFieldSyncRequest bodys, SyncCommon syncCommon, String apiUrl) {
        HttpHeaders headers = getHeaders(syncCommon);
        DataRequest dataRequest = new DataRequest();
        dataRequest.setParam(bodys);
        String url = syncCommon.getDomain() + apiUrl;
        String result = null;
        log.info("sync params {},header {}", dataRequest, headers);
        try {
            result = template.postForObject(url, new HttpEntity<>(dataRequest, headers), String.class);
            log.info("sync result {}", result);
        } catch (Exception e) {
            log.error("httpRequest error", e);
        }

        if (Objects.isNull(result)) {
            return null;
        }
        JSONObject resultObject = JSON.parseObject(result);
        if (null == resultObject) {
            return null;
        }
        String responseCode = resultObject.getString("responseCode");
        if (!SyncConstants.ON.equals(responseCode)) {
            String responseMessage = resultObject.getString("responseMessage");
            log.info("sync error {}", responseMessage);
            return null;
        }
        if (Objects.isNull(resultObject)) {
            return null;
        }
        return resultObject.getJSONObject("data");
    }


}
